﻿using HCMS.CommonDtos;
using HCMS.Entities.Base;
using HCMS.IRepositories.Base;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.EntityFrameworkCore;

namespace HCMS.Repositories.Base
{
    /// <summary>
    /// 行政区划 仓储层
    /// </summary>
    public class SystemAreaRepository : BaseRepository<SystemArea>, ISystemAreaRepository
    {
        public SystemAreaRepository(IDbContextProvider<BaseDbContext> dbContextProvider)
            : base(dbContextProvider)
        {
        }

        /// <summary>
        /// 管理 列表
        /// </summary>
        /// <param name="searchArgs">搜索 参数</param>
        /// <param name="pager">分页 参数</param>
        /// <returns></returns>
        public async Task<ListPagerDto<SystemArea>> ManageList(SearchArgsDto searchArgs, PagerArgsDto pager)
        {
            var query = await GetQueryableAsync();

            if (!string.IsNullOrWhiteSpace(searchArgs.SearchName) && !string.IsNullOrWhiteSpace(searchArgs.SearchKey))
            {
                switch (searchArgs.SearchName)
                {
                    case "name":
                        query = query.Where(t => t.Name.Contains(searchArgs.SearchKey));
                        break;
                    case "regionalismCode":
                        if (int.TryParse(searchArgs.SearchKey, out int regionalismCode))
                        {
                            query = query.Where(t => t.RegionalismCode == regionalismCode);
                        }
                        else
                        {
                            query = query.Where(t => 1 == 2);
                        }
                        break;
                    case "areaCode":
                        query = query.Where(t => t.AreaCode == searchArgs.SearchKey);
                        break;
                    case "postCode":
                        if (int.TryParse(searchArgs.SearchKey, out int postCode))
                        {
                            query = query.Where(t => t.PostCode == postCode);
                        }
                        else
                        {
                            query = query.Where(t => 1 == 2);
                        }
                        break;
                }
            }

            if (searchArgs.Status != 9999)
            {
                query = query.Where(t => t.Status == searchArgs.Status);
            }

            if (searchArgs.SearchRange != 2)
            {
                query = query.Where(t => t.ParentId == searchArgs.ParentId);
            }

            var count = await query.CountAsync();
            pager.RowCount = count;

            var list = new List<SystemArea>();

            if (count > 0)
            {
                query = query.OrderBy(t => t.RegionalismCode);

                list = await query
                           .Skip((pager.CurrentPageIndex - 1) * pager.PageSize)
                           .Take(pager.PageSize)
                           .ToListAsync();
            }

            var result = new ListPagerDto<SystemArea>()
            {
                Data = list ?? new List<SystemArea>(),
                PagerInfo = pager
            };

            return result;
        }

        /// <summary>
        /// 字典 树
        /// </summary>
        /// <returns></returns>
        public async Task<object> GetAllTree()
        {
            var query = await GetQueryableAsync();
            var all = await query.ToListAsync();

            all.Add(new SystemArea()
            {
                Name = "根节点",
                ParentId = -1
            });

            // 递归 构建树
            Func<int, bool, object> funcTree = null;
            funcTree = delegate (int parentId, bool isRoot)
            {
                Func<SystemArea, bool> where = (a => a.Id == 0 && a.ParentId == -1);
                if (!isRoot)
                {
                    where = (a => a.ParentId == parentId);
                }

                var obj = all.Where(where).OrderBy(t => t.RegionalismCode).Select(a => new
                {
                    id = a.Id,
                    name = a.Name,
                    status = a.Status,
                    createTime = a.CreateTime,
                    createUser = a.CreateUser,
                    updateTime = a.UpdateTime,
                    updateUser = a.UpdateUser,
                    children = funcTree(a.Id, false)
                }).ToList();

                return obj;
            };

            return funcTree(0, true);
        }

        /// <summary>
        /// 根据 省份 Id 删除数据
        /// </summary>
        /// <remarks>
        ///  物理删除
        /// </remarks>
        /// <param name="provinceId">省份 Id</param>
        /// <returns></returns>
        public async Task<bool> DelByProvinceId(int provinceId)
        {
            string sql = string.Format("DELETE FROM system_area WHERE parent_path LIKE '%0,{0}%' OR id = {0} ", provinceId);
            var result = await GetDbContextAsync().Result.Database.ExecuteSqlRawAsync(sql);
            return result > 0;
        }

    }
}
